<?php
class Delivery_Model_Mapper_Tags
	extends Delivery_Model_Mapper_Abstract
{
	
	public function getDbTable()
	{
		return parent::getDbTable( 'Tags' );
	}
	
	public function save( $tags )
	{
	}
	
	public function delete( $zona )
	{
	}
	
	/**
	 * @param int $idTag
	 * @return object Delivery_Model_Tag
	 */
	public function getById( $idTag )
	{
		if ( $this->getIdentityMap()->isRegistered( 'Delivery_Model_Tag', $idTag )){
			return $this->getIdentityMap()->get( 'Delivery_Model_Tag', $idTag );
		}
		
		$dbTable= $this->getDbTAble();
		$row	= $dbTable->getById( $idTag );
	
		if( empty($row) ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::TAG_NOT_FOUND );
		}
		
		return $this->_fetch( $row );
	}
	
	/**
	 * @param string $name
	 * @return object Delivery_Model_Tag
	 */
	public function getByName( $nombre ){		
		
		$dbTable= $this->getDbTAble();
		$row = $dbTable->getByName( $nombre );
		
		if( empty($row) ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::TAG_NOT_FOUND );
		}
		
		return $this->_fetch( $row );
	}
	
	public function getByTypeAndName( $tagType, $tagName ){
		
		$dbTable= $this->getDbTAble();
		$row	= $dbTable->getByTypeAndName( $tagType, $tagName );
		
		if( empty($row) ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::TAG_NOT_FOUND );
		}
		
		return $this->_fetch( $row );
	}
	
	
	public function getByIds( $ids )
	{
		$dbTable= $this->getDbTAble();
		
		return $this->_fetchCollection(
			'Tags',
			$dbTable->getByIds( $ids )
		);
	}
	
	public function getAll()
	{
		$dbTable= $this->getDbTAble();
		
		return $this->_fetchCollection(
			'Tags',
			$dbTable->getAll()
		);
	}
	
	public function getByType( $idTagType ){
		
		$dbTable= $this->getDbTAble();
		
		return $this->_fetchCollection(
			'Tags',
			$dbTable->getByType( $idTagType )
		);
	}	
	
	public function getLinked( $idCiudad = null )
	{
		$rowset = $this->getDbTAble()->getLinked( $idCiudad );
		$all = array();
		
		foreach ($rowset as $row){
			
			$tag = $this->_fetch( $row );
			$tipo = $tag->getTipo();
			
			isset($all[$tipo]) OR
				$all[$tipo] = array();
			
			
			$all[$tipo][]=array(
				'tag'=> $tag,
				'num'=> $row['cantidad']
			);
		}
		
		return $all;
	}
	
	/**
	 * @param array
	 * @return object Delivery_Model_Tag
	 */
	protected function _fetch( $row )
	{
		$tag = new Delivery_Model_Tag( $row );
		
		$this->getIdentityMap()->set( $tag, $tag->getId() );
		
		return $tag;
	}
	
}